package com.explam.springboot.controller.admin;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.explam.springboot.common.ResultUtil;
import com.explam.springboot.entity.User;
import com.explam.springboot.entity.UserVo;
import com.explam.springboot.exception.ServiceException;
import com.explam.springboot.mapper.IncomeMapper;
import com.explam.springboot.mapper.PayMapper;
import com.explam.springboot.service.IIncomeService;
import com.explam.springboot.service.IPayService;
import com.explam.springboot.service.IUserService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/admin/user")
public class UserController {

    @Resource
    private IUserService userService;

    @Resource
    private PayMapper payMapper;

    @Resource
    private IncomeMapper incomeMapper;

    @PostMapping("/login")
    public ResultUtil login(@RequestBody User user) {
        String username = user.getUsername();
        String password = user.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return ResultUtil.error(ResultUtil.ERROR_CODE, "请输入用户名和密码");
        }
        User user1 = userService.login(user);
        return ResultUtil.success(user1);
    }

    //注册
    @PostMapping("/register")
    public ResultUtil register(@RequestBody User user) {
        String username = user.getUsername();
        String password = user.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return ResultUtil.error(ResultUtil.ERROR_CODE, "参数错误");
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        User one = userService.getOne(wrapper);
        if (Objects.nonNull(one)) {
            throw new ServiceException(ResultUtil.ERROR_CODE, "账号已存在");
        }
        QueryWrapper<User> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("email", user.getEmail());
        List<User> list = userService.list(wrapper2);
        if (Objects.nonNull(list)&&list.size()>0) {
            throw new ServiceException(ResultUtil.ERROR_CODE, "邮箱已被存在");
        }
        String md5 = SecureUtil.md5(password);
        user.setUsername(username);
        user.setNickname(username);
        user.setPassword(md5);
        user.setStatus(0);
        user.setIsAdmin(1); //默认不是管理员
        user.setCreateTime(LocalDateTimeUtil.now());
        userService.save(user);
        return ResultUtil.success("注册成功");
    }

    //个人信息
    @GetMapping("/username")
    public ResultUtil findOne(@RequestParam String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return ResultUtil.success(userService.getOne(queryWrapper));
    }

    //新增
    @PostMapping("save")
    public ResultUtil save(@RequestBody User user) {
        userService.save(user);
        return ResultUtil.success();
    }

    //新增和修改
    @PostMapping("/update")
    public ResultUtil update(@RequestBody User user) {
        //是空时注册
        if(StringUtils.isEmpty(user.getId())){
            String username = user.getUsername();
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("username", username);
            User one = userService.getOne(wrapper);
            if (Objects.nonNull(one)) {
                throw new ServiceException(ResultUtil.ERROR_CODE, "账号已存在");
            }
            user.setPassword("123456"); //默认密码123456
        }

        userService.saveOrUpdate(user);
        return ResultUtil.success();
    }

    //修改密码
    @PostMapping("/change/pass")
    public ResultUtil changePass(String userId,String oldPassword,String newPassword) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id", userId);
        User one = userService.getOne(wrapper);
        String md5 = SecureUtil.md5(newPassword);
        String md52 = SecureUtil.md5(oldPassword);
        if(!md52.equals(one.getPassword())){
            throw new ServiceException(ResultUtil.ERROR_CODE, "旧密码错误");
        }
        one.setPassword(md5);
        userService.saveOrUpdate(one);
        return ResultUtil.success();
    }

    //删除  @PathVariable表示url参数 {id}必须与下面的参数id保持一致
    @GetMapping("/delete/id={id}")
    public ResultUtil delete(@PathVariable Integer id) {
        return ResultUtil.success(userService.removeById(id));
    }

    //批量删除数据
    @PostMapping("/del/batch")
    public ResultUtil deleteBatch(@RequestBody List<Integer> ids) {
        userService.removeBatchByIds(ids);
        return ResultUtil.success();
    }

    //查询所有数据
    @GetMapping("/all")
    public ResultUtil findAll() {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.select("id", "username", "nickname");
        List<User> list = userService.list(wrapper);
        return ResultUtil.success(list);
    }

    //根据id查询
    @GetMapping("/get-user/id={id}")
    public ResultUtil findOne(@PathVariable Integer id) {

        return ResultUtil.success(userService.getById(id));
    }
    //分页查询 @RequestParam接收 ?pageNum = 1 &pageSize = 10
    @GetMapping("/page")
    public ResultUtil findPage(@RequestParam Integer pageNum,
                               @RequestParam Integer pageSize,
                               @RequestParam(defaultValue = "") String nickname,
                               @RequestParam(defaultValue = "") String phone
    ) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        if (!"".equals(nickname)) {
            queryWrapper.like("nickname", nickname);
        }
        if (!"".equals(phone)) {
            queryWrapper.like("phone", phone);
        }
        queryWrapper.orderByDesc("id");
        Page<User> page = userService.page(new Page<>(pageNum, pageSize), queryWrapper);

        List list=new ArrayList();
        for(User user : page.getRecords()) {
            Integer id = user.getId(); //查询该用户本月的收入和指出
            Double totalPayAmount = payMapper.getTotalPayAmount(id);
            Double totalIncomeAmount = incomeMapper.getTotalIncomeAmount(id);
            UserVo userVo = new UserVo();
            userVo.setId(id);
            userVo.setUsername(user.getUsername());
            userVo.setNickname(user.getNickname());
            userVo.setSex(user.getSex());
            userVo.setEmail(user.getEmail());
            userVo.setPhone(user.getPhone());
            userVo.setAddress(user.getAddress());
            userVo.setAvatarUrl(user.getAvatarUrl());
            userVo.setStatus(user.getStatus());
            userVo.setRole(user.getRole());
            userVo.setIsAdmin(user.getIsAdmin());
            userVo.setCreateTime(user.getCreateTime());
            userVo.setPayTotal(totalPayAmount);
            userVo.setIncomeTotal(totalIncomeAmount);
            list.add(userVo);
        }
        Page page1 = new Page();
        page1.setRecords(list);
        page1.setCurrent(pageNum);
        page1.setSize(pageSize);
        return ResultUtil.success(page1);

    }
}